import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  ParseIntPipe,
  Query,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiParam,
} from '@nestjs/swagger';
import { BettingService } from './betting.service';
import { CreateBettingDto } from './dto/create-betting.dto';
import { UpdateBettingDto } from './dto/update-betting.dto';
import { Betting } from './entities/betting.entity';

@ApiTags('投注管理')
@Controller('betting')
export class BettingController {
  constructor(private readonly bettingService: BettingService) {}

  @ApiOperation({ summary: '创建投注选项' })
  @ApiResponse({ status: 201, description: '创建成功', type: Betting })
  @Post()
  create(@Body() createBettingDto: CreateBettingDto) {
    return this.bettingService.create(createBettingDto);
  }

  @ApiOperation({ summary: '更新投注选项' })
  @ApiResponse({ status: 200, description: '更新成功', type: Betting })
  @ApiParam({ name: 'id', description: '投注ID' })
  @Patch(':id')
  update(
    @Param('id', ParseIntPipe) id: number,
    @Body() updateBettingDto: UpdateBettingDto,
  ) {
    return this.bettingService.update(id, updateBettingDto);
  }

  @ApiOperation({ summary: '根据比赛ID获取投注选项' })
  @ApiResponse({ status: 200, description: '获取成功', type: [Betting] })
  @ApiParam({ name: 'matchId', description: '比赛ID' })
  @Get('match/:matchId')
  findByMatchId(@Param('matchId', ParseIntPipe) matchId: number) {
    return this.bettingService.findByMatchId(matchId);
  }

  @ApiOperation({ summary: '更新比赛结果' })
  @ApiResponse({ status: 200, description: '更新成功' })
  @ApiParam({ name: 'matchId', description: '比赛ID' })
  @Post('match/:matchId/result')
  updateMatchResult(
    @Param('matchId', ParseIntPipe) matchId: number,
    @Body() body: { homeScore: number; awayScore: number },
  ) {
    return this.bettingService.updateMatchResult(matchId, body.homeScore, body.awayScore);
  }

  @ApiOperation({ summary: '更新推荐结果' })
  @ApiResponse({ status: 200, description: '更新成功', type: Betting })
  @ApiParam({ name: 'id', description: '投注ID' })
  @Patch(':id/recommended')
  updateRecommendedResult(
    @Param('id', ParseIntPipe) id: number,
    @Body() body: { recommendedResult: ('win' | 'draw' | 'lose')[] },
  ) {
    // console.log('控制器接收到的请求体:', JSON.stringify(body));
    // console.log('推荐结果字段:', body.recommendedResult);
    return this.bettingService.updateRecommendedResult(id, body.recommendedResult);
  }

  @ApiOperation({ summary: '获取投注统计信息' })
  @ApiResponse({ 
    status: 200, 
    description: '获取成功',
    schema: {
      type: 'object',
      properties: {
        total: { type: 'number', description: '总投注数' },
        hitCount: { type: 'number', description: '命中数' },
        missCount: { type: 'number', description: '未命中数' },
        hitRate: { type: 'string', description: '命中率' },
      },
    },
  })
  @Get('statistics')
  getStatistics(@Query('matchId', ParseIntPipe) matchId?: number) {
    return this.bettingService.getStatistics(matchId);
  }
}